package com.taptech.doufu.ui.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.taptech.doufu.util.ScreenUtil2;
import com.taptech.doufu.sdk.universalimageloader.core.ImageLoader;
import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.util.DensityUtil;
import com.taptech.doufu.util.FetchResourceUtil;
import com.taptech.doufu.util.ScreenBrightnessUtil;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.SinaWeiboActivity;
import com.taptech.doufu.ui.adapter.TTShareAdapter;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.constant.Constant.WXData;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.util.ActivityUtil;
import com.taptech.doufu.util.DataCleanManager;
import com.taptech.doufu.util.UIUtil;
import com.douhuayuedu.douhua.wxapi.WXUtil;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;


public class SettingsFuntion
{


    //
    //

    private Animation mOperatingAnim;

    private PopupWindow mLoadingPanel;
    private View mLoadingView;
    private ImageView mRotateOfPanel;
    private TextView mInfoOfPanel;

    //
    //
    //private Button mMsgButton;
    // center
    public PopupWindow mCenterSharePopupWindow;
    private View mCenterShareView;
    private GridView mCenterShareGridView;

    // umeng share
    //	private UMSocialService mController; // common

    // wx
    private IWXAPI wxAPI;
    private Context mContext;


    private AlertDialog mMsgAlertDialog;
    private TextView mMsgInfoTextView;


    // settings
    public PopupWindow mSettingsPopupWindow;
    private View mSettingsView;
    private View mSettingsIndicator;
    private int mSettingsViewHeight;

    private TextView mSmallTextView;
    private TextView mMiddleTextView;
    private TextView mBigTextView;

    //
    private SeekBar mSeekBarEnableOfPanel;
    private SeekBar mSeekBarDisableOfPanel;

    private Button mSwitcherOfPanel;

    public boolean isDisSetting = false;
    private int mFontSizeType;
    private int mBrightnessValue;
    private int mBrightnessMode;

    private boolean mSystemIsAutoMode;
    private int mSystemBrightnessValue;

    private float mBrightnessScale = 0.01f;
    private int mBaseBrightnessValue = 10;

    public boolean isFinish = true;

    public SettingsFuntion(Context mContext)
    {
        this.mContext = mContext;
        makeCenterSharePopupWindow();
        registerShareServices();
        loadingPanel();
        makeSettingsPopupWindow();
    }

    private void registerShareServices()
    {
        // wx
        wxAPI = WXAPIFactory.createWXAPI(mContext, Constant.WX_APP_ID, true);
        wxAPI.registerApp(Constant.WX_APP_ID);
    }

    private void makeCenterSharePopupWindow()
    {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        mCenterShareView = inflater.inflate(R.layout.popup_share_center_panel, null);


        mCenterSharePopupWindow = new PopupWindow(mContext);
        mCenterSharePopupWindow.setContentView(mCenterShareView);


        //
        mCenterShareGridView = (GridView) mCenterShareView.findViewById(R.id.gv_popup_share_center_content);
        TTShareAdapter adapter = new TTShareAdapter(mContext);
        mCenterShareGridView.setAdapter(adapter);

        mCenterShareGridView.setOnItemClickListener(new OnItemClickListener()
        {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
            {
                // TODO Auto-generated method stub

                if (isPopupWindowCanHide(mCenterSharePopupWindow))
                {
                    mCenterSharePopupWindow.dismiss();
                }

                Bitmap bmp = FetchResourceUtil.fetchBitmap(mContext.getResources(), R.drawable.new_icon);

                //Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, WXData.THUMB_WIDTH_SIZE, WXData.THUMB_HEIGHT_SIZE, true);

                //UMImage uImage = new UMImage(getApplicationContext(), bmp);

                switch (arg2)
                {
                    case TTShareAdapter.SHARE_TO_SINA_WEIBO:
                        Intent intent = new Intent(mContext, SinaWeiboActivity.class);
                        intent.putExtra("flag", 2);
                        intent.putExtra("content", "靠！竟然被我发现了这个屌炸天的应用：豆花。里面的内容实在是太劲爆了，完全不敢直视啊！你们也快下来玩一下吧！@豆花客户端 下载地址：http://api.doufu.douhuayuedu.com/down.php?ref=wb");
                        mContext.startActivity(intent);
                        break;

                    case TTShareAdapter.SHARE_TO_WEIXIN:

                        shareToWeixin(mContext.getString(R.string.share_app_wechat_title), mContext.getString(R.string.share_app_wechat_url), bmp);
                        break;

                    case TTShareAdapter.SHARE_TO_PENGYOUQUAN:
                        shareToPengyouquan(mContext.getString(R.string.share_app_wechat_title), mContext.getString(R.string.share_app_wechat_url), bmp);
                        break;

                    case TTShareAdapter.SHARE_TO_MESSAGE:
                        //					shareToMessage();
                        shareToMessage("你的好朋友邀请您下载全球第一宅腐圈应用：豆花。下载地址：http://api.doufu.douhuayuedu.com/down.php?ref=dx");
                        break;

                    case TTShareAdapter.SHARE_TO_EMAIL:
                        shareToEmail("给你介绍一个屌炸天的应用", "最近发现一个屌炸天的应用：豆花。里面的内容太劲爆了，你也赶紧下载一个玩玩！下载地址：http://api.doufu.douhuayuedu.com/down.php?ref=yj");
                        break;

                    default:
                        break;
                }


            }
        });

        mCenterSharePopupWindow.setWidth(ScreenUtil2.getScreenWidthPixel((Activity) mContext) - DensityUtil.dip2px(mContext, 20));
        mCenterSharePopupWindow.setHeight(RelativeLayout.LayoutParams.WRAP_CONTENT);

        mCenterSharePopupWindow.setAnimationStyle(R.style.Animations_GrowFromBottom);
        mCenterSharePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mCenterSharePopupWindow.setOutsideTouchable(true);
        mCenterSharePopupWindow.setFocusable(true);

    }

    private void makeSettingsPopupWindow()
    {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        mSettingsView = inflater.inflate(R.layout.popup_settings_panel, null);

        mSettingsPopupWindow = new PopupWindow(mContext);
        mSettingsPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener()
        {

            @Override
            public void onDismiss()
            {
                // TODO Auto-generated method stub
                isDisSetting = true;
                //				invalidateOptionsMenu();
            }
        });
        mSettingsPopupWindow.setContentView(mSettingsView);
        mSettingsIndicator = (View) mSettingsView.findViewById(R.id.v_popup_settings_indicator);
        mSmallTextView = (TextView) mSettingsView.findViewById(R.id.tv_popup_settings_fontsize_small);

        mSmallTextView.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub

                mFontSizeType = Constant.Settings.VALUE_FONT_SIZE_TYPE_SMALL;
                updateFontSizeSelection(mFontSizeType);
            }
        });

        mMiddleTextView = (TextView) mSettingsView.findViewById(R.id.tv_popup_settings_fontsize_middle);

        mMiddleTextView.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub

                mFontSizeType = Constant.Settings.VALUE_FONT_SIZE_TYPE_MIDDLE;
                updateFontSizeSelection(mFontSizeType);
            }
        });

        mBigTextView = (TextView) mSettingsView.findViewById(R.id.tv_popup_settings_fontsize_big);

        mBigTextView.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                mFontSizeType = Constant.Settings.VALUE_FONT_SIZE_TYPE_BIG;
                updateFontSizeSelection(mFontSizeType);
            }
        });

        mSeekBarEnableOfPanel = (SeekBar) mSettingsView.findViewById(R.id.sb_popup_settings_brightness_enable);
        mSeekBarDisableOfPanel = (SeekBar) mSettingsView.findViewById(R.id.sb_popup_settings_brightness_disable);


        // should before onSeekBarChangeListener
        mSeekBarEnableOfPanel.setProgress(settingsToProgress(mBrightnessValue));
        mSeekBarDisableOfPanel.setProgress(settingsToProgress(mBrightnessValue));

        // should after setProgress
        mSeekBarEnableOfPanel.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
        {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar)
            {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar)
            {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
            {
                // TODO Auto-generated method stub
                if (mBrightnessMode == Constant.Settings.VALUE_BRIGHTNESS_MODE_MANUAL)
                {
                    /*wParams.screenBrightness = progressToBrightness(progress);

					getWindow().setAttributes(wParams);*/

                    mBrightnessValue = (int) (progressToBrightness(progress) * 255);

                    ScreenBrightnessUtil.setBrightness((Activity) mContext, mBrightnessValue);

                    if (mSeekBarDisableOfPanel != null)
                    {
                        mSeekBarDisableOfPanel.setProgress(progress);
                    }
                }

            }
        });


        mSeekBarDisableOfPanel.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
        {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar)
            {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar)
            {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
            {
                // TODO Auto-generated method stub
                if (mBrightnessMode == Constant.Settings.VALUE_BRIGHTNESS_MODE_MANUAL)
                {
                    /*wParams.screenBrightness = progressToBrightness(progress);

					getWindow().setAttributes(wParams);*/

                    mBrightnessValue = (int) (progressToBrightness(progress) * 255);

                    ScreenBrightnessUtil.setBrightness((Activity) mContext, mBrightnessValue);
                }

            }
        });

        mSeekBarDisableOfPanel.setEnabled(false);


        mSwitcherOfPanel = (Button) mSettingsView.findViewById(R.id.btn_popup_settings_switcher);

        mSwitcherOfPanel.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                if (mBrightnessMode == Constant.Settings.VALUE_BRIGHTNESS_MODE_AUTO)
                {

                    //mCheckOfPanel.setBackgroundResource(R.drawable.background_icon_uncheck);
                    mSwitcherOfPanel.setBackgroundResource(R.drawable.background_popup_settings_user);
                    mSwitcherOfPanel.setTextColor(mContext.getResources().getColor(R.color.popup_settings_text_user));
                    mBrightnessMode = Constant.Settings.VALUE_BRIGHTNESS_MODE_MANUAL;
                    mSeekBarEnableOfPanel.setVisibility(View.VISIBLE);
                    mSeekBarDisableOfPanel.setVisibility(View.GONE);

                    //Toast.makeText(getApplicationContext(), mSeekBarEnableOfPanel.getProgress() + ":enable", Toast.LENGTH_SHORT).show();

                    if (mSystemIsAutoMode)
                    {
                        ScreenBrightnessUtil.stopAutoBrightness((Activity) mContext);
                    } else
                    {

                        ScreenBrightnessUtil.setBrightness((Activity) mContext, mBrightnessValue);
                    }

                } else
                {
                    //Toast.makeText(getApplicationContext(), mSeekBarDisableOfPanel.getProgress() + ":disable", Toast.LENGTH_SHORT).show();

                    //mCheckOfPanel.setBackgroundResource(R.drawable.background_icon_check);
                    mSwitcherOfPanel.setBackgroundResource(R.drawable.background_popup_settings_system);
                    mSwitcherOfPanel.setTextColor(mContext.getResources().getColor(R.color.popup_settings_text_system));
                    mBrightnessMode = Constant.Settings.VALUE_BRIGHTNESS_MODE_AUTO;

                    mSeekBarEnableOfPanel.setVisibility(View.GONE);
                    mSeekBarDisableOfPanel.setVisibility(View.VISIBLE);


                    if (mSystemIsAutoMode)
                    {
                        ScreenBrightnessUtil.startAutoBrightness((Activity) mContext);
                    } else
                    {
                        ScreenBrightnessUtil.setBrightness((Activity) mContext, mSystemBrightnessValue);
                    }
                }
            }
        });

        //
        /*RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mSwitcherOfPanel.getLayoutParams();
        params.rightMargin = params.rightMargin - 4;
		mSwitcherOfPanel.setLayoutParams(params);*/

        //

        if (mBrightnessMode == Constant.Settings.VALUE_BRIGHTNESS_MODE_AUTO)
        {

            mSeekBarEnableOfPanel.setVisibility(View.GONE);
            mSeekBarDisableOfPanel.setVisibility(View.VISIBLE);

            mSwitcherOfPanel.setBackgroundResource(R.drawable.background_popup_settings_system);
            mSwitcherOfPanel.setTextColor(mContext.getResources().getColor(R.color.popup_settings_text_system));
        } else
        {
            mSeekBarEnableOfPanel.setVisibility(View.VISIBLE);
            mSeekBarDisableOfPanel.setVisibility(View.GONE);
            mSwitcherOfPanel.setBackgroundResource(R.drawable.background_popup_settings_user);
            mSwitcherOfPanel.setTextColor(mContext.getResources().getColor(R.color.popup_settings_text_user));
            if (mSystemIsAutoMode)
            {
                ScreenBrightnessUtil.stopAutoBrightness((Activity) mContext);
            } else
            {
                ScreenBrightnessUtil.setBrightness((Activity) mContext, mBrightnessValue);
            }
        }


        updateFontSizeSelection(mFontSizeType);

        mSettingsView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        mSettingsViewHeight = mSettingsView.getMeasuredHeight();

        mSettingsPopupWindow.setWidth(ScreenUtil2.getScreenWidthPixel((Activity) mContext) - DensityUtil.dip2px(mContext, 20));
        mSettingsPopupWindow.setHeight(RelativeLayout.LayoutParams.WRAP_CONTENT);

        mSettingsPopupWindow.setAnimationStyle(R.style.Animations_GrowFromBottom);
        mSettingsPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mSettingsPopupWindow.setOutsideTouchable(true);
        mSettingsPopupWindow.setFocusable(true);
    }

    private void updateFontSizeSelection(int type)
    {

        switch (type)
        {
            case Constant.Settings.VALUE_FONT_SIZE_TYPE_SMALL:
                mSmallTextView.setBackgroundResource(R.drawable.bg_settings_fontsize_pressed);
                mMiddleTextView.setBackgroundResource(R.drawable.bg_settings_fontsize_normal);
                mBigTextView.setBackgroundResource(R.drawable.bg_settings_fontsize_normal);
                break;

            case Constant.Settings.VALUE_FONT_SIZE_TYPE_MIDDLE:
                mSmallTextView.setBackgroundResource(R.drawable.bg_settings_fontsize_normal);
                mMiddleTextView.setBackgroundResource(R.drawable.bg_settings_fontsize_pressed);
                mBigTextView.setBackgroundResource(R.drawable.bg_settings_fontsize_normal);
                break;
            case Constant.Settings.VALUE_FONT_SIZE_TYPE_BIG:
                mSmallTextView.setBackgroundResource(R.drawable.bg_settings_fontsize_normal);
                mMiddleTextView.setBackgroundResource(R.drawable.bg_settings_fontsize_normal);
                mBigTextView.setBackgroundResource(R.drawable.bg_settings_fontsize_pressed);
                break;
            default:
                break;
        }


    }

    private void loadingPanel()
    {
        // animation
        mOperatingAnim = AnimationUtils.loadAnimation(mContext, R.anim.progressbar_rotate_style);
        LinearInterpolator lin = new LinearInterpolator();
        mOperatingAnim.setInterpolator(lin);
        // loading
        mLoadingPanel = new PopupWindow(mContext);

        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        mLoadingView = (View) inflater.inflate(R.layout.popup_loading_panel, null);

        mRotateOfPanel = (ImageView) mLoadingView.findViewById(R.id.iv_popup_loading_rotate);
        mInfoOfPanel = (TextView) mLoadingView.findViewById(R.id.tv_popup_loading_info);

        mLoadingPanel.setContentView(mLoadingView);

        mLoadingPanel.setWidth(LayoutParams.WRAP_CONTENT);
        mLoadingPanel.setHeight(LayoutParams.WRAP_CONTENT);

        mLoadingPanel.setBackgroundDrawable(new BitmapDrawable());
        mLoadingPanel.setOutsideTouchable(false);
        mLoadingPanel.setFocusable(false);
    }


    private void shareToWeixin(String title, String url, Bitmap bmp)
    {


        WXWebpageObject webpageObj = new WXWebpageObject();
        webpageObj.webpageUrl = url;


        WXMediaMessage msg = new WXMediaMessage();
        msg.title = title;
        msg.mediaObject = webpageObj;

        if (bmp != null)
        {
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, WXData.THUMB_WIDTH_SIZE, WXData.THUMB_HEIGHT_SIZE, true);
            msg.thumbData = WXUtil.bmpToByteArray(thumbBmp, true);
        }

        msg.description = mContext.getString(R.string.share_app_wechat_description);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.scene = SendMessageToWX.Req.WXSceneSession; // for wechat friends
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;

        wxAPI.sendReq(req);
    }


    private void shareToPengyouquan(String title, String url, Bitmap bmp)
    {
        if (wxAPI.getWXAppSupportAPI() < Constant.WXData.PENG_YOU_QUAN_MIN_VERSION_CODE)
        {
            Toast.makeText(mContext, R.string.info_share_pengyouquan_version_too_low, Toast.LENGTH_LONG).show();
            return;
        }

        WXWebpageObject webpageObj = new WXWebpageObject();
        webpageObj.webpageUrl = url;


        WXMediaMessage msg = new WXMediaMessage();
        msg.title = title;
        msg.mediaObject = webpageObj;

        if (bmp != null)
        {
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, WXData.THUMB_WIDTH_SIZE, WXData.THUMB_HEIGHT_SIZE, true);
            msg.thumbData = WXUtil.bmpToByteArray(thumbBmp, true);
        }

        msg.description = mContext.getString(R.string.share_app_wechat_description);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.scene = SendMessageToWX.Req.WXSceneTimeline; // for pengyou quan
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;

        wxAPI.sendReq(req);

    }

    private void shareToEmail(String shareTitle, String shareText)
    {
        try
        {
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.putExtra(Intent.EXTRA_SUBJECT, shareTitle);
            intent.putExtra(Intent.EXTRA_TEXT, shareText);
            mContext.startActivity(intent);

        } catch (ActivityNotFoundException e)
        {
            Toast.makeText(mContext, mContext.getString(R.string.info_email_start_failed), Toast.LENGTH_LONG).show();
        }
    }


    /**
     * 发短信
     *
     * @param smsBody
     */

    private void shareToMessage(String smsBody)

    {
        Uri smsToUri = Uri.parse("smsto:");

        Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);

        intent.putExtra("sms_body", smsBody);

        mContext.startActivity(intent);

    }

    private void shareToSystemMore()
    {

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "你的好朋友邀请您下载全球第一宅腐圈应用：豆花。下载地址：http://api.doufu.la/down.php?ref=dx");
        intent.putExtra(Intent.EXTRA_TEXT, mContext.getString(R.string.share_app_description));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(Intent.createChooser(intent, mContext.getString(R.string.share_title)));
    }

    public boolean isPopupWindowCanHide(PopupWindow window)
    {

        if (this != null && !((Activity) mContext).isFinishing() && window != null)
        {
            return true;
        }

        return false;
    }



    public void gotoClearCache(View parent)
    {
        if (mLoadingPanel != null)
        {
            mLoadingPanel.showAtLocation(parent, Gravity.CENTER, 0, 0);
            if (mOperatingAnim != null)
            {
                mRotateOfPanel.startAnimation(mOperatingAnim);
            }

            mInfoOfPanel.setText(R.string.info_clearing);
        }

        new ClearCacheTask().execute();

    }

    private Handler mLoadingHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case 0:

                    break;
                case 1:

                    if (mRotateOfPanel != null)
                    {
                        //mRotateOfPanel.setVisibility(View.GONE);
                        mRotateOfPanel.clearAnimation();
                    }

                    break;

                case 2:
                    if (mContext != null && !((Activity) mContext).isFinishing() && mLoadingPanel != null)
                    {
                        mLoadingPanel.dismiss();
                    }

                    break;
                default:
                    break;
            }

        }
    };

    public void gotoClearAppData(View parent)
    {
        if (mLoadingPanel != null)
        {
            mLoadingPanel.showAtLocation(parent, Gravity.CENTER, 0, 0);
            if (mOperatingAnim != null)
            {
                mRotateOfPanel.startAnimation(mOperatingAnim);
            }

            mInfoOfPanel.setText(R.string.info_clearing_app);
            //SharedPreferenceUtil.saveTypeWithCookie(mContext,"0");
        }

        new ClearAppDataTask().execute();

    }

    class ClearAppDataTask extends AsyncTask<Void, Void, String>
    {

        @Override
        protected String doInBackground(Void... params)
        {
            // TODO Auto-generated method stub
            DataCleanManager.cleanApplicationData(mContext, Constant.AppDir.DIR_HOME);
            CacheUtil.clearCacheByUser();
            ImageLoader imageLoader = ImageLoader.getInstance();
            if (imageLoader != null) {
                imageLoader.clearDiscCache();
                imageLoader.clearMemoryCache();
            }
            AccountService.getInstance().clearAccount();
            ActivityUtil.saveInfoInSharedPreference(mContext);
            try
            {
                Thread.sleep(1000);
            } catch (Exception e)
            {
            }

            mLoadingHandler.sendEmptyMessage(1);

            mLoadingHandler.sendEmptyMessage(2);

            return null;
        }

        @Override
        protected void onPostExecute(String result)
        {
            showAlertDialog(mContext.getString(R.string.restartApp));
        }


    }

    class ClearCacheTask extends AsyncTask<Void, Void, String>
    {

        @Override
        protected String doInBackground(Void... params)
        {
            // TODO Auto-generated method stub

            CacheUtil.clearCacheByUser();
            ImageLoader imageLoader = ImageLoader.getInstance();
            if (imageLoader != null)
            {
                imageLoader.clearDiscCache();
                imageLoader.clearMemoryCache();
            }

            try
            {
                Thread.sleep(1000);
            } catch (Exception e)
            {
                // TODO: handle exception
            }


            mLoadingHandler.sendEmptyMessage(1);

            mLoadingHandler.sendEmptyMessage(2);

            return null;
        }

        @Override
        protected void onPostExecute(String result)
        {
            UIUtil.toastMessage(mContext, "清除缓存完毕");
        }


    }

    protected void showAlertDialog(String msg)
    {
        if (isFinish)
        {
            mMsgAlertDialog = new AlertDialog.Builder(mContext).create();
            mMsgAlertDialog.show();
            mMsgAlertDialog.setContentView(R.layout.popup_message_restart);
            mMsgInfoTextView = (TextView) mMsgAlertDialog.findViewById(R.id.tv_message_info);
            mMsgInfoTextView.setText(msg);
            mMsgAlertDialog.setCancelable(false);
        }
    }

    private float progressToBrightness(int progress)
    {
        return (progress + mBaseBrightnessValue) * mBrightnessScale;
    }

    private int settingsToProgress(int brightness)
    {
        TTLog.e("settingsToProgress", (int) (brightness * 100.0f / 255 - mBaseBrightnessValue) + "");
        return (int) (brightness * 100.0f / 255 - mBaseBrightnessValue);
    }
}
